<?php
/**
* @author moufer<moufer@163.com>
* @copyright (c)2001-2014 Moufersoft
* @website www.modoer.com
*/

!defined('IN_MUDDER') && exit('Access Denied');

/**
 * 微站模型
 */
class msm_weixin_member_bind extends ms_model
{
	public $table = 'dbpre_weixin_member_bind';
	public $key = 'id';
	public $model_flag = 'weixin';

	public function get_sign_hash($mp_openid, $user_openid, $time)
	{
		return create_formhash($mp_openid, $user_openid, $time);
	}

	public function __construct()
	{
		parent::__construct();
		$this->model_flag = 'weixin';
		$this->modcfg = $this->variable('config');
	}

	public function check_sign()
	{
		$time = strtotime(date('Y-m-d'), $this->timestamp);
		$hash = _input('hash', '');
		$sign = _input('sign', '');

		//openid解析
		$data = explode("\t", authcode($hash, 'DECODE'));

		if($sign == self::get_sign_hash($data[0], $data[1] , $time)) {
			return $data;
		}
		$this->add_error('微信绑定参数验证失败，请返回微信通过绑定连接重新进入绑定。');
		return false;
	}

	public function read_by_openid($mp_openid, $user_openid) {
		return $this->db->from($this->table)
			->where(array('mp_openid' => $mp_openid, 'user_openid' => $user_openid))
			->get_one();
	}

	public function bind() {

		if(!$data = $this->check_sign()) {
			return false;
		}
		list($mp_openid, $user_openid, $user_unionid) = $data;

		$username = _post('username', '', MF_TEXT);
		$password = _post('password','');

		//检测是否能登录，并返回登录会员数据
		$login_mdl	= $this->loader->model('member:login');
		$member		= $login_mdl->check_login($username, $password);
		if(!$member) {
			//登录失败，返回所悟信息
			$this->add_error($login_mdl);
			return false;
		}

		if($this->exists($mp_openid, $user_openid)) {
			return $this->add_error('对不起，微信帐号已绑定。');
		}

		//添加记录
		$insert = array(
			'mp_openid' 		=> $mp_openid,
			'user_openid' 	=> $user_openid,
			'user_unionid' 	=> $user_unionid,
			'uid' 			=> (int)$member['uid'],
			'dateline'		=> TIMESTAMP,
			'ip'			=> _G('ip'),
		);

		$this->db->from($this->table)
			->set($insert)
			->insert();
		return $this->db->insert_id();
	}

	public function unbind($mp_openid, $user_openid) {
		return $this->db->from($this->table)
					->where(array('mp_openid' => $mp_openid, 'user_openid' => $user_openid))
					->delete();
	}

	/**
	 * 检查帐号是否绑定
	 * @param  string $mp_openid 公众号openid
	 * @param  string $openid    会员微信openid
	 * @return array            返回绑定数据
	 */
	public function exists($mp_openid, $user_openid)
	{
		return $this->read_by_openid($mp_openid, $user_openid);
	}

}

/* end */